<!doctype html>
<html>
<head>
    <title>Caliper</title>
    <meta charset="UTF-8"/>
    <style type="text/css">
        a:link, a:visited {
            text-decoration: none;
            color: #2980b9;
            border-bottom: 1px solid #2980b9;
        }
        a:hover{
            text-decoration: none;
            color: #ff0000;
            border-bottom: 1px solid #ff0000;
        }
        .left-column {
            position: fixed;
            width:20%;
            border-radius: 5px;
            background-color: #f2f2f2;
        }
        .right-column {
            margin-left: 22%;
            width:60%;
        }
        .left-column ul,h2 {
            display: block;
            margin: 10px;
            padding: 0;
            list-style: none;
        }
        .left-column ul{
            border-top: 1px solid #d9d9d9;
            font-size:14px;
        }
        .left-column li,select{
            margin-bottom: 5px;
            color: #5e6b73;
        }
        .left-column h3 {
            border-left: 5px solid #009a61;
        }
        .left-column h3>button {
            border: 0;
            width: 60px;
            height: 28px;
            text-align: center;
            border-radius: 5px;
            color: #fff;
            background: #2980b9;
            cursor: pointer;
            float:right;
        }
        .left-column select {
            width: 60%;
        }
        .right-column>div {
            border-top: 1px solid #d9d9d9;
        }
        .right-column ul {
            display: block;
            padding: 0;
            list-style: none;
        }
        .right-column li{
            margin-bottom: 10px;
        }
        .right-column p {
            display: inline-block;
            font-family: verdana,arial,sans-serif;
            font-size:11px;
        }
        .tag {
            display: inline-block;
            padding: 5px 10px;
            background: #2980b9;
            font-family: verdana,arial,sans-serif;
            font-size:11px;
            color: #fff;
            text-align: center;
            border-radius: 5px;
        }
        .chart {
            height:240px;
            border:1px solid #d9d9d9;
            padding: 0px;
        }
        .right-column pre {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            background-color: #f2f2f2;
            overflow:auto;
            height:300px;
            white-space: pre-line;
            font-size: 12px;
        }
    </style>
</head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.0.4/echarts.min.js"></script>
<script type="text/javascript">
    var sut = "fabric";
    const sutConf = {
        fabric: {
            config: "config.json"
        },
        sawtooth: {
            config: "config-sawtooth.json"
        }
    };
    var running = false;
    var bench = "simple";
    var pageHtmlJson  = null;
    var charts = {
        throughput : {
            obj: null,
            element: 'chartThroughput',
            data: ['submitted', 'succeeded', 'failed'],
            xAxis: 'time',
            yAxis: 'tps',
        },
        latency : {
            obj: null,
            element: 'chartLatency',
            data: ['max', 'min', 'avg'],
            xAxis: 'time',
            yAxis: 'second',
        }
    };
    var chartInited = false;
    var es = null;

    function selectSUT(value) {
        var eleType = document.getElementById("suttype");
        var eleSize = document.getElementById("sutsize");
        if(value === "fabric") {
            sut = "fabric";
            eleType.innerHTML = "Fabric v1.0.0";
            eleSize.innerHTML = "4 Peers, 1 Orderer(solo)";
        }
        if(value === "stl") {
            sut = "sawtooth";
            eleType.innerHTML = "Sawtooth v0.8.0";
            eleSize.innerHTML = "4 Validators";
        }
    }

    function selectBenchmark(value) {
        var eleName = document.getElementById("benName");
        var eleInfo = document.getElementById("benInfo");
        if(value === "simple") {
            eleName.innerHTML = "Simple Benchmark";
            eleInfo.innerHTML = "This is an example benchmark for caliper, to test the backend DLT&#39;s performance with simple account opening &amp; querying transactions";
        }
        else {
            eleName.innerHTML = value + " Benchmark";
            eleInfo.innerHTML = "Not provided yet";
        }
    }


    function loadXMLDoc(xmlhttp, url, cfunc) {
        // xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange=cfunc;
        xmlhttp.open("GET", url, true);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        xmlhttp.send();

    }

    function initChart(id) {
        charts[id].obj = echarts.init(document.getElementById(charts[id].element));
    }

    function refreshChart(id) {
        if(charts[id].obj !== null) {
            var opt = getOption(id);
            charts[id].obj.setOption(opt);
        }
    }

    function getOption(id) {
        var opt = {
            tooltip: { trigger: 'axis' },
            animation: false,
            legend: { data: charts[id].data},
            xAxis: {
                name: charts[id].xAxis,
                data: pageHtmlJson[id].x
            },
            yAxis: {
                type: 'value',
                name: charts[id].yAxis
            },
            series:[]
        }
        var data = charts[id].data;
        //var colors = ['#32cd32', '#da70d6', '#87cefa', '#2980b9'];
        //var colorLen = 4;
        for(let i = 0; i < data.length ; i++) {
            opt.series.push({
                name: data[i],
                type: 'line',
                stack: '',
                symbolSize: 1,
                itemStyle:{
                    normal: {
                        lineStyle: {
                            width:2,
                        }
                    }
                },
                data: pageHtmlJson[id][data[i]]
            });
        }
        return opt;
    }

    function refreshTxInfo(sub, succ, fail) {
        var txinfo = document.getElementById("txInfo");
        txinfo.innerHTML = 'Submitted: '+sub+', Succeeded: '+succ+', Failed: '+fail;
    }

    function initCharts() {
        if(!chartInited) {
            for(let key in charts) {
                initChart(key);
            }
            chartInited = true;
        }
    }



    function changeRunningStatus(value) {
        running = value;
        var btn  = document.getElementById("runBtn");
        if(running){
            btn.innerHTML = "Running";
            btn.style.background = "#5e6b73";
            document.getElementById("report").href = "#";
            initCharts();
            refreshTxInfo(0,0,0);
        }
        else {
            btn.innerHTML = "Run";
            btn.style.background = "#2980b9";
            chartInited = false;
        }
    }

    function run() {
        if (running) {
            return;
        }

        if(!sutConf.hasOwnProperty(sut)) {
            alert('unknown sut type:' + sut);
            return;
        }
        if(bench !== 'simple') {
            alert('sorry, this demo only supports ^simple^ benchmark');
            return;
        }

        changeRunningStatus(true);
        setTimeout( function () {
            if(es !== null) {
                es.close();
            }
            es = new EventSource("remotecontrol.php?b="+bench+"&s="+sutConf[sut].config);
            es.addEventListener('error', function(e) {
                changeRunningStatus(false);
                es.close();
                es = null;
            });
            es.addEventListener('message', function(e) {
                var msg = JSON.parse(e.data);
                switch(msg.type) {
                    case 'finish':
                        changeRunningStatus(false);
                        es.close();
                        es = null;
                        if(msg.data !== 'ok') {
                            alert(msg.data);
                        }
                        break;
                    case 'report':
                        document.getElementById('report').href = 'report.html';
                        window.open('report.html');
                        break;
                    case 'log':
                        let item = document.getElementById("benchlog");
                        item.innerHTML = msg.data;
                        item.scrollTop = item.scrollHeight;
                        break;
                    case 'metrics':
                        pageHtmlJson = JSON.parse(msg.data);
                        if(pageHtmlJson !== null && chartInited) {
                            for(let key in charts) {
                                refreshChart(key);
                            }
                        }
                        if(pageHtmlJson !== null && pageHtmlJson.hasOwnProperty('summary')) {
                            refreshTxInfo(pageHtmlJson.summary.txSub, pageHtmlJson.summary.txSucc, pageHtmlJson.summary.txFail);
                        }
                        break;
                    case 'debug':
                        alert(msg.data);
                        break;
                    default:
                        alert('unknown message:'+msg.name);
                        break;
                }
            });
        }, 100);
    }

    function bye() {
        if(es !== null) {
            es.close();
            es = null;
        }
        chartInited = false;
        var xmlhttp = new XMLHttpRequest();
        loadXMLDoc(xmlhttp, "stop.php", function(){
            // do nothing
        });
    }

</script>
<body onbeforeunload="bye()">

<main>
    <div class="left-column">
        <h2>Caliper</h2>
        <ul>
            <h3>&nbspSystem Under Test</h3>
            <select onChange="selectSUT(this.value)">
                <option value="fabric" selected="selected">Fabric Sample Network</option>
                <option value="stl">Sawtooth Sample Network</option>
            </select>
            <li><strong>Version: &nbsp</strong><span ID="suttype">Fabric v1.0.0</span></li>
            <li><strong>Size: &nbsp</strong><span ID="sutsize">4 Peers, 1 Orderer(solo)</span></li>
            <li><strong>Distribution: &nbsp</strong><span ID="sutdist">Single Host</span></li>
        </ul>
        <ul>
            <h3>&nbspBenchmark
                <button  ID='runBtn' onclick="run()">Run</button>
            </h3>
            <select onChange="selectBenchmark(this.value)">
                <option value="simple" selected="selected">Simple</option>
                <option value="drm">DRM</option>
                <option value="IOT">IOT</option>
                <option valut="fin">Finance</option>
            </select>
            <li><strong>Name: &nbsp</strong><span ID="benName">Simple Benchmark</span></li>
            <li><strong>Description: &nbsp</strong><span ID="benInfo">This is an example benchmark for caliper, to test the backend DLT&#39;s performance with simple account opening &amp; querying transactions</span></li>
            <li><a id="report" href="#">report</a></li>
            <!--<li><a href="#benchmarkInfo">Details</a></li>-->

        </ul>
        <ul>
            <h3>&nbspMore Information</h3>
            <li><a href="https://github.com/Huawei-OSG/caliper/blob/master/README.md">Introduction</a></li>
            <li><a href="https://github.com/Huawei-OSG/caliper/blob/master/docs/Architecture.md">Architecture</a></li>
            <li><a href="https://github.com/Huawei-OSG/caliper/">Source code</a></li>
        </ul>

    </div>
    <div class="right-column">
        <div>
            <h3>Performance</h3>
            <ul>
                <li><strong class="tag">Transactions</strong></li>
                <li><p ID="txInfo">Submitted: 0, Succeeded: 0, Failed: 0</p></li>
                <li><strong class="tag">Throughput</strong></li>
                <li><div class="chart" ID="chartThroughput"></div></li>
                <li><strong class="tag">Latency</strong></li>
                <li><div class="chart" ID="chartLatency"></div></li>
            </ul>
        </div>
        <div>
            <h3>Log</h3>
            <pre ID="benchlog">waiting for benchmark to start</pre>
        </div>
    </div>

</main>

</body>
</html>
